package com.tianruan.dc.common.annotation.condition;

import com.tianruan.dc.common.utils.ApiVersionUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * @PS 版本控制器请求条件实现类
 */
@Data
@Slf4j
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition>  {

    /**
     * 接口路径中的版本号前缀，如: api/v[1-n]/fun
     */
    public final static String VERSION_PREFIX = "(v|V)\\d+(\\.(\\d|_)+){0,}";
    private String apiVersion;

    public ApiVersionCondition(String apiVersion) {
        this.apiVersion = apiVersion;
    }
    /**
     * 最近优先原则，方法定义的 @ApiVersion > 类定义的 @ApiVersion
     */
    @Override
    public ApiVersionCondition combine(ApiVersionCondition other) {
        return new ApiVersionCondition(other.getApiVersion());
    }
    /**
     * 获得符合匹配条件的ApiVersionCondition
     */
    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
        String[] bomVersionList = request.getRequestURI().split("/");
        for (String version: bomVersionList) {
            // 校验版本格式是否正确
            boolean matches = version.matches(VERSION_PREFIX);
            if (matches) {
                version = version.toLowerCase();
                if (ApiVersionUtil.compareVersion(version, getApiVersion()) >= 0) {
                    return this;
                }
            }
        }
        return null;
    }
    /**
     * 当出现多个符合匹配条件的ApiVersionCondition，优先匹配版本号较大的
     */
    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
        return ApiVersionUtil.compareVersion(other.getApiVersion(), getApiVersion());
    }

}
